﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Linq;
using System.Web;
using System.Xml;
using Aandelendelen.String;

namespace Aandelendelen.News
{
	public class NewsItemCollection : Collection<NewsItem>
	{
		internal NewsItemCollection()
		{
			this.ReadNews();
		}

		private void ReadNews()
		{
			string path = HttpContext.Current.Server.MapPath("/App_Data/News.xml");

			XmlDocument doc = new XmlDocument();

			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/aandelendelen/news/item");

			if (nodes != null)
			{
				foreach (XmlNode node in nodes)
				{
					if (node.Name == "item")
					{
						NewsItem newsItem = this.ReadNewsItem(node);

						//don't read items older than six months
						TimeSpan dif = DateTime.Now.Subtract(newsItem.Date);

						if (dif.Days > 183)
							break;

						this.Add(newsItem);
					}
				}
			}
		}

		private NewsItem ReadNewsItem(XmlNode node)
		{
			DateTime date;
			string content = "";
			string title = "";

			string dt = node.Attributes["date"].Value;

			date = DateTime.Parse(dt);

			foreach (XmlNode childNode in node.ChildNodes)
			{
				switch (childNode.Name)
				{
					case "content": content = childNode.InnerXml.Clean();
						break;
					case "title": title = childNode.InnerText;
						break;
				}
			}

			NewsItem newsItem = new NewsItem(date, title, content);

			return newsItem;
		}
	}
}